package com.ct.ah.lab.controller;

import com.ct.ah.lab.entity.User;
import com.ct.ah.lab.exception.UserException;
import com.ct.ah.lab.service.IUserService;
import com.wf.captcha.utils.CaptchaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Base64;
import java.util.Base64.Decoder;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/users")
public class UserController {
    @Autowired
    private IUserService userService;

//    @RequestMapping("/hello")
//    @ResponseBody
//    public String hello() {
//        return "hello";
//    }

    @RequestMapping("/regist")
    @ResponseBody
    public Map<String, Object> regist(User user, String captcha, HttpServletRequest req) {
        Map<String, Object> map = new HashMap<>();
        if (!CaptchaUtil.ver(captcha, req)) {
            map.put("msg", "error Captcha");
            return map;
        }

        try {
            userService.regist(user);
            map.put("state", 1000);
        } catch (Exception e) {
            map.put("msg", e.getMessage());
        }
        return map;
    }

    @RequestMapping("/checkUsername")
    @ResponseBody
    public Map<String, Object> checkUsername(String username) {
        boolean checkUsername = userService.checkUsername(username);
        Map<String, Object> map = new HashMap<>();
        if (checkUsername) {
            map.put("state", 1000);
            map.put("msg", "true");
        } else {
            map.put("state", 1000);
            map.put("msg", "false");
        }
        return map;
    }

    @RequestMapping("/login")
    @ResponseBody
    public Map<String, Object> login(String username, String password, String captcha, HttpServletRequest req) {
        Map<String, Object> map = new HashMap<>();

        if (!CaptchaUtil.ver(captcha, req)) {
            CaptchaUtil.clear(req);  // 清除session中的验证码
//            HttpSession session = req.getSession();
//            System.out.println(session.getAttribute("captcha"));
            map.put("msg", "error Captcha");
            return map;
        }

        try {
            HttpSession session = req.getSession();
            User loginUser = userService.login(username, password);
            session.setAttribute("loginUser", loginUser);
            loginUser.setPassword("");
            map.put("state", 1000);
            map.put("data", loginUser);
        } catch (UserException e) {
            map.put("msg", e.getMessage());
        }

        return map;
    }


    @RequestMapping("/checkLogin")
    @ResponseBody
    public Map<String, Object> checkLogin(HttpServletRequest req) {
        Map<String, Object> map = new HashMap<>();
        HttpSession session = req.getSession();

        try {
            User user = (User) session.getAttribute("loginUser");
            System.out.println(user);
            if (user != null) {
                map.put("state", 1000);
            } else {
                map.put("msg", "not login");
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg", "not login");
        }

        return map;
    }

    @RequestMapping("/getUserInfo")
    @ResponseBody
    public Map<String, Object> getUserInfo(HttpServletRequest req) {
        Map<String, Object> map = new HashMap<>();
        HttpSession session = req.getSession();

        try {
            User user = (User) session.getAttribute("loginUser");
            user.setPassword("");
            System.out.println(user);
            if (user != null) {
                map.put("state", 1000);
                map.put("user", user);
                map.put("userInfo", user);
            } else {
                map.put("msg", "not login");
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg", "not login");
        }

        return map;
    }

    //changePassword
    @RequestMapping("/changePassword")
    @ResponseBody
    public Map<String, Object> changePassword(String oldPassword, String newPassword, HttpServletRequest req) {
        Map<String, Object> map = new HashMap<>();

        try {
            HttpSession session = req.getSession();

            User loginUser = (User) session.getAttribute("loginUser");
            userService.changePassword(loginUser, oldPassword, newPassword);
            map.put("state", 1000);
        } catch (UserException e) {
            map.put("msg", e.getMessage());
        }

        return map;
    }

    //changePassword
    @RequestMapping("/logout")
    @ResponseBody
    public Map<String, Object> logout(HttpServletRequest req) {
        Map<String, Object> map = new HashMap<>();

        try {
            HttpSession session = req.getSession();

            session.removeAttribute("loginUser");
            map.put("state", 1000);
        } catch (UserException e) {
            map.put("msg", e.getMessage());
        }

        return map;
    }

    @RequestMapping("/updateUserInfo1")
    @ResponseBody
    public Map<String, Object> updateUserInfo1(User user, String imageData, HttpServletRequest req) {
        Map<String, Object> map = new HashMap<>();

        try {
            HttpSession session = req.getSession();
            User loginUser = (User) session.getAttribute("loginUser");

            loginUser.setUsernameFull(user.getUsernameFull());
            loginUser.setPhone(user.getPhone());

            userService.changeUserInfo(loginUser);

            map.put("state", 1000);
        } catch (UserException e) {
            map.put("msg", e.getMessage());
        }

        return map;
    }


    @RequestMapping("/updateUserInfo")
    @ResponseBody
    public Map<String, Object> updateUserInfo(User user, String imageData, String imageName, HttpServletRequest req) {
        Map<String, Object> map = new HashMap<>();

        try {
            HttpSession session = req.getSession();
            User loginUser = (User) session.getAttribute("loginUser");

            if (!imageName.equals("") && !imageData.equals("")) {
                int index = imageData.lastIndexOf(",");
                //去除data:image/jpeg;base64,前缀
                if (index != -1) {
                    imageData = imageData.substring(index + 1);
                }

                String imgName = imageName;

                Decoder decode = Base64.getDecoder();
                byte[] byteImg = decode.decode(imageData);//把base64转成字节码
                System.out.println(imgName);
                int hc = imgName.hashCode();
                String hex = Integer.toHexString(hc);//16进制字符串

                /*
                 * 创建文件夹
                 */

                String tmp_path = loginUser.getUid().toString();
                String root = req.getServletContext().getRealPath("/avatar");
                System.out.println(root);
                File dirFile = new File(root, "/" + tmp_path);//取前16进制的前两个字符串创建二级目录
                dirFile.mkdirs();//创建目录
                String imgNewName = imgName;
                try {
                    OutputStream out = new FileOutputStream(dirFile + "/" + imgNewName);//保存
                    out.write(byteImg);//写入文件
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //新图片地址
                String newAdd = req.getServletContext().getContextPath() + "/avatar/" + tmp_path + "/" + imgNewName;
                System.out.println(newAdd);
                loginUser.setAvatar(newAdd);
            }


            loginUser.setUsernameFull(user.getUsernameFull());
            loginUser.setPhone(user.getPhone());

            userService.changeUserInfo(loginUser);

            map.put("state", 1000);
        } catch (UserException e) {
            map.put("msg", e.getMessage());
        }

        return map;
    }


}
